#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <time.h>
#include <pthread.h>

#define MINHAPORTA 3334    						/* Porta que os usuarios irão se conectar*/
#define BACKLOG 10     							/* Quantas conexões pendentes serão indexadas */


//*******************************************************************************************************************
//*															Pacotes                                                 *
//*******************************************************************************************************************

	char status_pkg[16] = {0x0a, 'S', 'T', 'A','T','U','S', 'C', 'M', '_', 'D','E','A','D',0x0d,'\0'};
	
	char aciona_pkg1[32] = {0x0a, 'A', 'C', 'I','O','N','A', 'M', 'E', 'N', 'T','O','C','M','_', 'D','E','A','D','_','S','1','=','O','N','3','0','0','0',0x0d,'\0'};
	char aciona_pkg2[50] = {0x0a, 'A', 'C', 'I','O','N','A', 'M', 'E', 'N', 'T','O','C','M','_', 'D','E','A','D','_','S','1','=','O','N','0','6','0','0','_','S','3','=','O','N','0','2','0','0',0x0d,'\0'};
	char aciona_pkg3[60] = {0x0a, 'A', 'C', 'I','O','N','A', 'M', 'E', 'N', 'T','O','C','M','_', 'D','E','A','D','_','S','1','=','O','N','3','0','0','0','_','S','2','=','O','N','0','6','0','6','_','S','3','=','O','N','0','2','0','0',0x0d,'\0'};
	char aciona_pkg4[70] = {0x0a, 'A', 'C', 'I','O','N','A', 'M', 'E', 'N', 'T','O','C','M','_', 'D','E','A','D','_','S','1','=','O','N','0','6','0','0','_','S','2','=','O','N','1','2','0','0','_','S','3','=','O','N','1','8','0','0','_','S','4','=','O','N','2','4','0','0',0x0d,'\0'};
	
	char alteraip_pkg_3333[50] = {0x0a, 'A', 'L', 'T','E','R','A', 'I', 'P', 'C', 'M','_','D','E','A', 'D','_','2','0','1','.','2','5','.','2','4','.','8','4','_','3','3','3','3',0x0d,'\0'};
	char alteraip_pkg_3335[50] = {0x0a, 'A', 'L', 'T','E','R','A', 'I', 'P', 'C', 'M','_','D','E','A', 'D','_','2','0','1','.','2','5','.','2','4','.','8','4','_','3','3','3','5',0x0d,'\0'};
	
	char status_pkg_erro[16] = {0x0a, 'S', 'T', 'A','T','U','S', 'C', 'M', '_', 'F','0','0','5',0x0d,'\0'};
	char aciona_pkg_erro[32] = {0x0a, 'A', 'C', 'I','O','N','A', 'M', 'E', 'N', 'T','O','C','M','_', 'F','0','0','5','_','S','1','=','O','N','3','0','0','0',0x0d,'\0'};	
	char alteraip_pkg_erro[50] = {0x0a, 'A', 'L', 'T','E','R','A', 'I', 'P', 'C', 'M','_','F','0','0', '5','_','2','0','1','.','2','5','.','2','4','.','8','4','_','3','3','3','3',0x0d,'\0'};
		
	char manda_configuracao_OP0_pkg[30] = {0x0a, 'C', 'O', 'N', 'F', 'I', 'G', '_', 'U','_', '1', '2', '3', '4', '5', '6', '7', '8', '_', '0', '.', '0' , '.', '0', '1', '_', '0', '0', '0', 0x0d};
	char manda_configuracao_OP3_pkg[30] = {0x0a, 'C', 'O', 'N', 'F', 'I', 'G', '_', 'U','_', '1', '2', '3', '4', '5', '6', '7', '8', '_', '0', '.', '0' , '.', '0', '1', '_', '0', '0', '3', 0x0d};
	
	char manda_configuracao_Down_OP0_pkg[30] = {0x0a, 'C', 'O', 'N', 'F', 'I', 'G', '_', 'D','_', '1', '2', '3', '4', '5', '6', '7', '8', '_', '0', '.', '0' , '.', '0', '1', '_', '0', '0', '0', 0x0d};
	char manda_configuracao_Down_OP3_pkg[30] = {0x0a, 'C', 'O', 'N', 'F', 'I', 'G', '_', 'D','_', '1', '2', '3', '4', '5', '6', '7', '8', '_', '0', '.', '0' , '.', '0', '1', '_', '0', '0', '3', 0x0d};
	
	char manda_configuracao_pkg_erro[30] = {0x0a, 'C', 'O', 'N', 'F', 'I', 'G', '_', 'U','_', '1', '2', '3', '5', '5', '6', '7', '8', '_', '0', '.', '0' , '.', '0', '1', '_', '0', '0', '0', 0x0d};
		
	char pacote_parteX[10] = {0x0a, 'P', 'A', 'R', 'T', 'E', 0};	
	char pacote_parteF[10] = {0x0a, 'P', 'A', 'R', 'T', 'E', 'F', 0};
	
	char pac1[] = "1:1_001_737000_21_0_001_737000_22_";
	char pac2[] = "2:F004_";
	char pac3[] = "3:1_801_2_30_2_0_1_30_";
	char pac4[] = "4:803_1_12032700_11114400_00_00_1_1_3_";
	char pac5[] = "5:1_804_030_1_1_0000_";
	char pac6[] = "6:0_0_120_";
	char pac7[] = "7:302_301_";
	char pac8[] = "8:2_";
	char pac9[] = "9:800_";
	char pac10[] = "10:0_";
	char pac11[] = "11:0_966_010_";
	char pac12[] = "12:0_967_15_0_";
	char pac13[] = "13:40_";
	char pac14[] = "14:802_";
	char pac15[] = "15:12345678_";
	char pac16[] = "16:0_3_1_1_1_003_000_***_000_***_000_***_000_***_000_***_00_00_00_00_00_0_1_0_";
//	char pac16[] = "16:0_3_1_1_1_003_000_000_000_000_000_000_000_000_000_000_00_00_00_00_00_0_1_0_";
	char pac17[] = "17:0_130_***_0_0_0_0_0_0_0_0_000_***_0_0_0_0_0_0_0_0_000_***_0_0_0_0_0_0_0_0_000_***_0_0_0_0_0_0_0_0_000_***_0_0_0_0_0_0_0_0_";
//	char pac17[] = "17:0_130_000_0_0_0_0_0_0_0_0_000_000_0_0_0_0_0_0_0_0_000_000_0_0_0_0_0_0_0_0_000_000_0_0_0_0_0_0_0_0_000_000_0_0_0_0_0_0_0_0_";
	char pac18[] = "18:2_015_2_015_2_015_2_015_";
	char pac19[] = "19:www.cafrecnet.com.br_3333_";
	char pac20[] = "20:1_1_1_192.168.1.1_255.255.255.0_192.168.1.1_8.8.8.8_8.8.4.4_1_www.terra.com.br_www.googe.com.br_1_";
	char pac21[] = "21:1_30_1_1_1010_Leon_Ezequiel_senha_1_1_1111_Leon2_Ezequiel2_senha2_0_987_0_";
	char pac22[] = "22:1_123_1_555.555_2_666.666_1_1_0_950_1_333_";
	char pac22_1[] = "23:www.cafrecnet.com.br_3333_";
	char pac23[] = "48:1_1_6119_I#_800500_6118_100_6118_010_6118_100_6118_100_6118_100_6118_001_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_";
	char pac23_1[] = "I#_800600_6117_030_6117_030_6117_030_6119_030_6117_030_6117_003_6117_030_6119_030_6119_030_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_";
	char pac23_2[] = "I#_800800_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_";
	char pac23_3[] = "I#_800700_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_6119_000_";
	char pac24[] =   "50:I#_12345_leonEze_32055555_EndCliente_I#_000000____I#_000000____I#_000000____I#_000000____I#_000000____I#_000000____I#_000000____I#_000000____";
	char pac24_1[] =  "I#_000000____I#_000000____I#_000000____I#_000000____I#_000000____I#_000000____I#_000000____I#_000000____I#_000000____I#_000000____I#_000000____";
	char pac25[] = "51:I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__";
	char pac25_1[] =  "I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__";
	char pac25_2[] =  "I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__";
	char pac25_3[] =  "I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__I#_000__0__";
	char pac26[] = "52:I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__";
	char pac26_1[] =  "I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__";
	char pac26_2[] =  "I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__I#_00__";
        
        
    char pacoterparte1[] = {0x0a, 'R', 'P', 'A', 'R', 'T', 'E','1', 0x0d}                         ;
    char pacoterparte2[] = {0x0a, 'R', 'P', 'A', 'R', 'T', 'E','2', 0x0d}                         ;
    char pacoterparte3[] = {0x0a, 'R', 'P', 'A', 'R', 'T', 'E','3', 0x0d}                         ;
    char pacoterparte4[] = {0x0a, 'R', 'P', 'A', 'R', 'T', 'E','4', 0x0d}                         ;
    char pacoterparte5[] = {0x0a, 'R', 'P', 'A', 'R', 'T', 'E','5', 0x0d}                         ;
    char pacoterparte6[] = {0x0a, 'R', 'P', 'A', 'R', 'T', 'E','6', 0x0d}                         ;
    char pacoterparte7[] = {0x0a, 'R', 'P', 'A', 'R', 'T', 'E','7', 0x0d}                         ;
    char pacoterparte8[] = {0x0a, 'R', 'P', 'A', 'R', 'T', 'E','8', 0x0d}                         ;
    char pacoterparteF[] = {0x0a, 'R', 'P', 'A', 'R', 'T', 'E','F', 0x0d}                         ;
                                        
//*******************************************************************************************************************
//*															Pacotes                                                 *
//*******************************************************************************************************************

int Meusocket, Novosocket;  					/* escuta em Meusocket, nova conexão em Novosocket */
struct sockaddr_in meu_endereco;   				/* informação do meu endereco */
struct sockaddr_in endereco_dele; 				/* informação do endereco do conector */
	
time_t start, stop;
clock_t ticks; long count;	

int qual_KA = 0;
int qual_Evento = 0;


void *Send_Status( ){
	
		
	int status_send;
	int op;
	
	char *tempMSN;
	
	tempMSN = malloc(sizeof(char)*1000);
	
	while(1){
		scanf("%d",&op);	
		switch ( op ){
			
			case 0: 
				time(&start);						
				status_send = write(Novosocket,status_pkg,16);
				printf("Status request send: \n");
				break;
					
			case 1:
				time(&start);						
				status_send = write(Novosocket,aciona_pkg1,30);
				printf("Aciona request send: \n");
				break;
				
			case 2:
				time(&start);						
				status_send = write(Novosocket,aciona_pkg2,50);
				printf("Aciona request send: \n");
				break;
			
			case 3:
				time(&start);						
				status_send = write(Novosocket,aciona_pkg3,60);
				printf("Aciona request send: \n");
				break;
			
			case 4:
				time(&start);						
				status_send = write(Novosocket,aciona_pkg4,70);
				printf("Aciona request send: \n");
				break;
				
			case 5:
				time(&start);						
				status_send = write(Novosocket,alteraip_pkg_3333,50);
				printf("Altera IP request send: \n");
				break;
			
			case 6:
				time(&start);						
				status_send = write(Novosocket,alteraip_pkg_3335,50);
				printf("Altera IP request send: \n");
				break;
				
			case 10:
				time(&start);						
				status_send = write(Novosocket,status_pkg_erro,16);
				printf("Status request errado send: \n");
				break;
				
			case 11:
				time(&start);						
				status_send = write(Novosocket,aciona_pkg_erro,32);
				printf("Aciona request errado send: \n");
				break;
				
			case 12:
				time(&start);						
				status_send = write(Novosocket,alteraip_pkg_erro,32);
				printf("Altera IP request errado send: \n");
				break;				
				
			
			case 20:
								
				if (qual_KA==0){
					qual_KA=1;
				}else{
					qual_KA=0;
				}
				
				if (qual_KA==0){
					printf("\tKA aprovado\n\n");
				}else{
					printf("\tKA não aprovado \n\n");
				}
				break;
			
			case 21:
								
				if (qual_Evento==0){
					qual_Evento=1;
				}else{
					qual_Evento=0;
				}
				
				if (qual_Evento==0){
					printf("\tEventos aprovado\n\n");
				}else{
					printf("\tEventos não aprovado \n\n");
				}
				break;
				
			case 30:
				time(&start);						
				status_send = write(Novosocket,manda_configuracao_OP0_pkg,30);
				printf("Mandado Requisição de configuração com op 0 \n");
				break;		
				
			case 31:
				time(&start);						
				status_send = write(Novosocket,manda_configuracao_OP3_pkg,30);
				printf("Mandado Requisição de configuração com op 3 \n");
				break;	
				
					
			case 32:
				time(&start);						
				status_send = write(Novosocket,manda_configuracao_Down_OP0_pkg,30);
				printf("Mandado Requisição de download configuração com op 3 \n");
				break;	
				
				
			case 33:
				time(&start);						
				status_send = write(Novosocket,manda_configuracao_Down_OP3_pkg,30);
				printf("Mandado Requisição de download configuração com op 0 \n");
				break;	
				
			case 35:
				time(&start);						
				status_send = write(Novosocket,manda_configuracao_pkg_erro,30);
				printf("Mandado Requisição de configuração senha errada\n");
				break;		
								
			case 41:
				time(&start);						
				sprintf(tempMSN,"%s1_%s%s%s%s%c",pacote_parteX,pac1,pac2,pac3,pac4,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 1\n\t%s\n\n", tempMSN);
				break;		
							
			case 42:
				time(&start);						
				sprintf(tempMSN,"%s2_%s%s%s%s%s%s%s%s%c",pacote_parteX,pac5,pac6,pac7,pac8,pac9,pac10,pac11,pac12,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 2\n\t%s\n\n", tempMSN);
				break;		
							
			case 43:
				time(&start);						
				sprintf(tempMSN,"%s3_%s%s%s%s%c",pacote_parteX,pac13,pac14,pac15,pac16,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 3\n\t%s\n\n", tempMSN);
				break;		
							
			case 44:
				time(&start);						
				sprintf(tempMSN,"%s4_%s%s%s%c",pacote_parteX,pac17,pac18,pac19,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 4\n\t%s\n\n", tempMSN);
				break;		
			
			case 45:
				time(&start);						
				sprintf(tempMSN,"%s5_%s%s%s%c",pacote_parteX,pac20,pac21,pac22_1,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 5\n\t%s\n\n", tempMSN);
				break;		
				
			case 451:
				time(&start);						
				sprintf(tempMSN,"%s6_%s%c",pacote_parteX,pac22,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 5\n\t%s\n\n", tempMSN);
				break;	
								
			case 46:
				time(&start);						
				sprintf(tempMSN,"%s7_%s%c",pacote_parteX,pac23,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 6\n\t%s\n\n", tempMSN);
				break;	
								
			case 461:
				time(&start);						
				sprintf(tempMSN,"%s8_%s%c",pacote_parteX,pac23_1,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 7\n\t%s\n\n", tempMSN);
				break;	
									
			case 462:
				time(&start);						
				sprintf(tempMSN,"%s9_%s%c",pacote_parteX,pac23_2,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 8\n\t%s\n\n", tempMSN);
				break;	
									
			case 463:
				time(&start);						
				sprintf(tempMSN,"%s10_%s%c",pacote_parteX,pac23_3,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 9\n\t%s\n\n", tempMSN);
				break;						
			
			case 47:
				time(&start);						
				sprintf(tempMSN,"%s11_%s%c",pacote_parteX,pac24,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 10\n\t%s\n\n", tempMSN);
				break;	
				
				
			case 471:
				time(&start);						
				sprintf(tempMSN,"%s12_%s%c",pacote_parteX,pac24_1,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 11\n\t%s\n\n", tempMSN);
				break;		
								
			case 48:
				time(&start);						
				sprintf(tempMSN,"%s13_%s%c",pacote_parteX,pac25,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 12\n\t%s\n\n", tempMSN);
				break;	
				
									
			case 481:
				time(&start);						
				sprintf(tempMSN,"%s14_%s%c",pacote_parteX,pac25_1,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 13\n\t%s\n\n", tempMSN);
				break;	
				
									
			case 482:
				time(&start);						
				sprintf(tempMSN,"%s15_%s%c",pacote_parteX,pac25_2,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 14\n\t%s\n\n", tempMSN);
				break;	
				
									
			case 483:
				time(&start);						
				sprintf(tempMSN,"%s16_%s%c",pacote_parteX,pac25_3,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 15\n\t%s\n\n", tempMSN);
				break;	
									
			case 49:
				time(&start);						
				sprintf(tempMSN,"%s17_%s%c",pacote_parteX,pac26,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 16\n\t%s\n\n", tempMSN);
				break;
			
									
			case 491:
				time(&start);						
				sprintf(tempMSN,"%s18_%s%c",pacote_parteX,pac26_1,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 17\n\t%s\n\n", tempMSN);
				break;
				
			case 40:
				time(&start);						
				sprintf(tempMSN,"%s_%s%c",pacote_parteF,pac26_2,0x0d);				 
				status_send = write(Novosocket,tempMSN,strlen(tempMSN));
				printf("Mandado PACOTE 18 FINAL\n\t%s\n\n", tempMSN);
				break;
				
								
			case 51:
				time(&start);						
				status_send = write(Novosocket,pacoterparte1,10);
				printf("Mandado RPARTE1 \n\n", tempMSN);
				break;	
			
			case 52:
				time(&start);						
				status_send = write(Novosocket,pacoterparte2,10);
				printf("Mandado RPARTE2 \n\n", tempMSN);
				break;	
				
			case 53:
				time(&start);						
				status_send = write(Novosocket,pacoterparte3,10);
				printf("Mandado RPARTE3 \n\n", tempMSN);
				break;	
				
			case 54:
				time(&start);						
				status_send = write(Novosocket,pacoterparte4,10);
				printf("Mandado RPARTE4 \n\n", tempMSN);
				break;	
				
			case 55:
				time(&start);						
				status_send = write(Novosocket,pacoterparte5,10);
				printf("Mandado RPARTE5 \n\n", tempMSN);
				break;	
				
			case 56:
				time(&start);						
				status_send = write(Novosocket,pacoterparte6,10);
				printf("Mandado RPARTE6 \n\n", tempMSN);
				break;	
					
			case 57:
				time(&start);						
				status_send = write(Novosocket,pacoterparte7,10);
				printf("Mandado RPARTE7 \n\n", tempMSN);
				break;	
				
			case 58:
				time(&start);						
				status_send = write(Novosocket,pacoterparte8,10);
				printf("Mandado RPARTE8 \n\n", tempMSN);
				break;	
				
			case 50:
				time(&start);						
				status_send = write(Novosocket,pacoterparteF,10);
				printf("Mandado RPARTEf \n\n", tempMSN);
				break;	
			
			default:
				printf("Tecla Inutil");
			break;		
		}		
	}
		
}

main(int argc, char *argv[])
{
	int tamanho;
	int tamanho_recebido;
	char buffer_read[500];
	char buffer_parser[500];
	int status_send;
	char entradacom;
	
	char keepalive_pkg[7] = { 0x0a, 'R', 'K', 'C', 'M', 0x0d, '\0'};
		
	char evento_pkg[7] = { 0x0a, 'R', 'E', 'C', 'M', 0x0d, '\0'};

	char keepalive_pkg_errado[7] = { 0x0a, 'R', 'K', 'C', 'D', 0x0d, '\0'};

	char keepalive_header[3] = { 'K', 'C', 'M'};
	char evento_header[3] = { 'E', 'C', 'M'};

	int consegui = 0;
	int i;
	
	pthread_t Escreve;
	time_t currentTime;
	struct tm *timeinfo;

	if (argc <= 1){
		
		printf("Número de argumentos insuficientes. RecNetSimulador <PORTA> \n\n");
				
		exit(0);
	}

	int porta_meu;

	porta_meu = atoi(argv[1]);


	system("clear");

	if ((Meusocket = socket(AF_INET, SOCK_STREAM, 0)) == -1)	/* Inicia Socket */
	{
		perror("não consegui criar socket");
		exit(1);
	}

	meu_endereco.sin_family = AF_INET;
	meu_endereco.sin_port = htons(porta_meu);
	meu_endereco.sin_addr.s_addr = INADDR_ANY; 			/* coloca IP automaticamente */
	bzero(&(meu_endereco.sin_zero), 8);        			/* Zera o resto da estrutura */
	
	/* Pega a hora atual do sistema. */
	currentTime= time(NULL);
	 
	/* Converte-o em uma estrutura tm. */
	timeinfo= localtime(&currentTime);
	 
	printf("\n\nSimulador de RecNet Leon\n");
	printf("Iniciado em: %02d:%02d:%02d\n\n", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
	printf("Meu Ip: %s\n",inet_ntoa(meu_endereco.sin_addr.s_addr));	
	printf("Minha porta %d\n", porta_meu);
	printf("Número maximo de conexoes %d\n\n", BACKLOG);

	printf("Deseja ver lista de comandos(s/n): ");
	scanf("%c", &entradacom);
	
	if (entradacom=='s'){	
		
		printf("Comandos: \n\n");
		
		printf(" Entrada 0 -> Comando request STATUS -> STATUSCM_DEAD\n\n");			
		
		printf(" Entrada 1 -> Comando aciona SAIDAS -> ACIONAMENTOCM_DEAD_S1=ON3000\n");			
		printf(" Entrada 2 -> Comando aciona SAIDAS -> ACIONAMENTOCM_DEAD_S1=ON0600_S3=ON0200\n");			
		printf(" Entrada 3 -> Comando aciona SAIDAS -> ACIONAMENTOCM_DEAD_S1=ON3000_S2=ON0606_S3=ON0200\n");			
		printf(" Entrada 4 -> Comando aciona SAIDAS -> ACIONAMENTOCM_DEAD_S1=ON0600_S2=ON1200_S3=ON1800_S4=ON2400\n\n");
		
		printf(" Entrada 5 -> Comando altera IP -> ALTERAIPCM_DEAD_201.25.24.84_3333\n");
		printf(" Entrada 6 -> Comando altera IP -> ALTERAIPCM_DEAD_201.25.24.84_3335\n\n");
	
		printf(" Entrada 10 -> Comando erro request STATUS -> STATUSCM_F005\n");			
		printf(" Entrada 11 -> Comando erro aciona SAIDAS -> ACIONAMENTOCM_F005_S1=ON3000\n");				
		printf(" Entrada 12 -> Comando erro altera IP -> ALTERAIPCM_F005_201.25.24.84_3333\n\n");
		
		printf(" Entrada 30 -> Comando configure UPLOAD -> CONFIG_U_12345678_0.0.01_000\n");
		printf(" Entrada 31 -> Comando configure UPLOAD -> CONFIG_U_12345678_0.0.01_003\n\n");
		
		printf(" Entrada 35 -> Comando erro configure UPLOAD -> CONFIG_U_12355678_0.0.01_000\n\n");
	
		printf(" Entrada 41 -> Comando configure PARTE -> PARTE1\n");			
		printf(" Entrada 42 -> Comando configure PARTE -> PARTE2\n");			
		printf(" Entrada 43 -> Comando configure PARTE -> PARTE3\n");			
		printf(" Entrada 44 -> Comando configure PARTE -> PARTE4\n");			
		printf(" Entrada 45 -> Comando configure PARTE -> PARTE5\n");
		printf(" Entrada 45 -> Comando configure PARTE -> PARTE5\n");
		printf(" Entrada 451 -> Comando configure PARTE -> PARTE6\n");
		printf(" Entrada 46 -> Comando configure PARTE -> PARTE5\n");
		printf(" Entrada 461 -> Comando configure PARTE -> PARTE7\n");
		printf(" Entrada 462 -> Comando configure PARTE -> PARTE8\n");
		printf(" Entrada 463 -> Comando configure PARTE -> PARTE9\n");
		printf(" Entrada 47 -> Comando configure PARTE -> PARTE10\n");
		printf(" Entrada 471 -> Comando configure PARTE -> PARTE11\n");
		printf(" Entrada 48 -> Comando configure PARTE -> PARTE12\n");
		printf(" Entrada 481 -> Comando configure PARTE -> PARTE13\n");
		printf(" Entrada 482 -> Comando configure PARTE -> PARTE14\n");
		printf(" Entrada 483 -> Comando configure PARTE -> PARTE15\n");
		printf(" Entrada 49 -> Comando configure PARTE -> PARTE16\n");
		printf(" Entrada 491 -> Comando configure PARTE -> PARTE17\n");
		printf(" Entrada 40 -> Comando configure PARTE -> PARTEF\n\n");
		
		printf("Informações especiais: Os comandos de KA mandados pela placa são automaticamente respondidos\n\t Para desativar esta opção Entrada -> 20\n\n");
		printf("Informações especiais: Os comandos de EVENTO mandados pela placa são automaticamente respondidos\n\t Para desativar esta opção Entrada -> 21\n\n");
	
	}	

	printf("\nIniciando conexao: \n");
	
	if (bind(Meusocket, (struct sockaddr *)&meu_endereco, sizeof(struct sockaddr))== -1) 
	{
		//perror("\nNão consegui Fazer bind no socket, provavelmente a última conexão não fio bem encerrada. Aguare um poco e reinicie o programa. Erro");
		//exit(1);
		printf("\nNão foi possível fazer bind no socket,\nprovavelmente a última conexão não foi bem encerrada.\nAguare um poco enquanto o Linux elimina o socket por timeout.\n");
		printf("\t");
		sleep(5);
	}else{
		consegui = 1;
	}	

	while (consegui == 0){
		if (bind(Meusocket, (struct sockaddr *)&meu_endereco, sizeof(struct sockaddr))== -1) 
		{
			sleep(5);
		}else{
			consegui = 1;
		}
	}

	printf("\n\n");
	printf("Bindo completo, socket a espera de conexao. Escutando:\n\n");

	if (listen(Meusocket, BACKLOG) < 0) 
	{
		perror("Não consigo escutar no soket - listen");
		exit(1);
	}

	
	
	
	while(1) {
		tamanho = sizeof(struct sockaddr_in);
		if ((Novosocket = accept(Meusocket, (struct sockaddr *)&endereco_dele,&tamanho)) < 0){
			perror("accept");
			continue;
		}
		printf("Conexão com %s estabelecida as %02d:%02d:%02d\n\n",inet_ntoa(endereco_dele.sin_addr), timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
		if (!fork()) {
			time(&start);	// inicia o timer
			
			status_send = pthread_create(&Escreve,NULL,Send_Status,NULL);
			
			while(1){

				for ( i=0; i<500;i++){
					buffer_read[i]='\0';
					buffer_parser[i]='\0';
				}				
				
				tamanho_recebido = read(Novosocket,buffer_read,450);	//mensagem recebida
				
				strncpy(buffer_parser, buffer_read+1,tamanho_recebido-2);

				/* Pega a hora atual do sistema. */
				currentTime= time(NULL);
	 
				/* Converte-o em uma estrutura tm. */
				timeinfo= localtime(&currentTime);

				if (buffer_parser[0]=='K'){
					printf("\tKAlive - %s - de %s as %02d:%02d:%02d\n\n", buffer_parser, inet_ntoa(endereco_dele.sin_addr), timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
					if (qual_KA==0){
						status_send = write(Novosocket,keepalive_pkg,7);
					}else{
						
					}
					
				}else if(buffer_parser[0]=='E'){
					printf("\tEvento - %s - de %s as %02d:%02d:%02d\n\n", buffer_parser, inet_ntoa(endereco_dele.sin_addr), timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
					if (qual_Evento==0){
						status_send = write(Novosocket,evento_pkg,6);
					}else{
						
					}
					
				}else if(buffer_parser[0]=='R'){
					printf("\tResposta - %s - de %s as %02d:%02d:%02d\n\n", buffer_parser, inet_ntoa(endereco_dele.sin_addr), timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
					
					
				}else if(buffer_parser[0]=='P'){
					printf("\tParte - %s - de %s as %02d:%02d:%02d\n\n", buffer_parser, inet_ntoa(endereco_dele.sin_addr), timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
					
					
				}else{
					printf(" Status - %s - de %s as %02d:%02d:%02d\n\n", buffer_parser, inet_ntoa(endereco_dele.sin_addr), timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
				}		
			}	
		}
		close(Novosocket);
		while(waitpid(-1,NULL,WNOHANG) > 0); /* Limpa o processo crianca.fork() */
	}
}



